class SceneMain extends Scene {
  constructor(game) {
    super(game)

    this.blocks = []
    this.paused = false


    this.paddle = Paddle()
    this.ball = Ball()


    for (let i = 0; i < 10; i++) {
      let block;
      if (i < 5) {
        block = Block(i * 100 + 100, 50)
      } else {
        block = Block((i - 5) * 100 + 100, 100)
      }
      this.blocks.push(block)
    }


    game.addAction('a', () => {
      this.paddle.moveLeft()
    });

    game.addAction('d', () => {
      this.paddle.moveRight()
    })

    game.addAction('f', () => {
      this.ball.fire()
    })

    window.addEventListener('keyup', (event) => {
      if (event.key === 'p') {
        this.paused = !this.paused
      }
    })


    var canDrag = false
    game.canvas.addEventListener('mousedown', (event) => {
      var x = event.offsetX
      var y = event.offsetY

      if (this.ball.hasPoint(x, y)) {
        canDrag = true
      } else {
        canDrag = false
      }

    });


    game.canvas.addEventListener('mousemove', (event) => {
      var x = event.offsetX
      var y = event.offsetY

      if (canDrag) {
        this.ball.setPosition(x, y)
      }

    });

    game.canvas.addEventListener('mouseup', () => {
      canDrag = false
    });

  }

  update() {



    if (this.paused) {
      return
    }
    this.ball.move()

    if (this.ball.y > this.paddle.y) {
      let end = SceneEnd.new(this.game)
      this.game.runWithScene(end)
    }


    // 判断挡板和球相撞
    if (this.paddle.collide(this.ball)) {
      this.ball.speedY *= -1
    }

    // 判断砖块和小球相撞
    this.blocks.forEach((block) => {
      if (block.intersect(this.ball)) {
        block.kill()
        this.ball.speedY *= -1
      }
    })
  }

  draw() {
    this.game.drawRect(this.paddle, 'red')
    this.game.drawRect(this.ball, 'blue')

    this.blocks.forEach((block) => {
      if (!block.alive) {
        return
      }
      this.game.drawRect(block, 'green')
    })
  }
}